package com.jadesoft.common.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.sitechasia.webx.core.exception.BaseUnCheckedException;
import com.sitechasia.webx.core.utils.base.PopulateUtil;
import com.ufida.leaf.exception.BusinessException;

@SuppressWarnings("unchecked")
public class Page implements Serializable {
	private static final long serialVersionUID = 2728437513842150372L;
	private int pageSize;
	private int start;
	private List data;
	private long totalCount;

	public Page() {
		this(0, 0L, 20, ((List) (new ArrayList())));
	}

	public Page(int start, long totalSize, int pageSize, List data) {
		this.pageSize = 20;
		if (pageSize <= 0 || start < 0 || totalSize < 0L) {
			throw new BaseUnCheckedException("Illegal Arguments!");
		} else {
			this.pageSize = pageSize;
			this.start = start;
			totalCount = totalSize;
			this.data = data;
			return;
		}
	}

	public long getTotalCount() {
		return totalCount;
	}

	public long getTotalPageCount() {
		return totalCount % (long) pageSize != 0L ? totalCount / (long) pageSize + 1L : totalCount / (long) pageSize;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setResult(List data) {
		this.data = data;
	}

	public List getResult() {
		return data;
	}

	public int getCurrentPageNo() {
		return start / pageSize + 1;
	}

	public boolean hasNextPage() {
		return (long) getCurrentPageNo() < getTotalPageCount();
	}

	public boolean getNextPage() {
		return hasNextPage();
	}

	public boolean getPreviousPage() {
		return hasPreviousPage();
	}

	public boolean hasPreviousPage() {
		return getCurrentPageNo() > 1;
	}

	public boolean isEmpty() {
		return data == null || data.isEmpty();
	}

	public int getStartIndex() {
		return (getCurrentPageNo() - 1) * pageSize;
	}

	public int getEndIndex() {
		int endIndex = getCurrentPageNo() * pageSize - 1;
		return (long) endIndex < totalCount ? endIndex : (int) totalCount - 1;
	}

	protected static int getStartOfPage(int pageNo) {
		return getStartOfPage(pageNo, 20);
	}

	public static int getStartOfPage(int pageNo, int pageSize) {
		return (pageNo - 1) * pageSize;
	}

	public Page transform(Class clazz) {
		List items = getResult();
		for (int i = 0; i < items.size(); i++) {
			try {
				Object dto = clazz.newInstance();
				PopulateUtil.populate(items.get(i), dto);
				items.set(i, dto);
			} catch (InstantiationException e) {
				throw new BusinessException(e);
			} catch (IllegalAccessException e) {
				throw new BusinessException(e);
			}
		}
		return this;
	}
	
	public int getStart() {
		return start;
	}

	public List getData() {
		return data;
	}
	
	public static void main(String[] args) {
		System.out.println(Page.class.getDeclaredFields().length);
	}

}